﻿using Microsoft.AspNetCore.Authorization;

namespace ServiceCore.WebApi.jwt
{
    public class JwtAuthorizationHandler : AuthorizationHandler<JwtAuthorizationRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, JwtAuthorizationRequirement requirement)
        {
            var httpContext = context.Resource as HttpContext;
            string apiName = string.Empty, httpToken = string.Empty;
            if (httpContext != null)
            {
                apiName = httpContext.Request.Path.Value;
                httpToken = httpContext.Request.Headers["Authorization"];
            }

            if (context.User == null)
            {
                //$"403-1.用户为空：{apiName}____{httpToken}".LogWriteService(LogServiceCore.LogServiceCore_Refresh);

                context.Fail();
                return Task.CompletedTask;
            }
            var userid = context.User.Claims.FirstOrDefault(p => p.Type == "userid")?.Value;
            var refreshToken = context.User.Claims.FirstOrDefault(p => p.Type == "refreshToken")?.Value;
            if (string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(refreshToken))
            {
                //$"403-2.用户或刷新token为空：{userid}-{refreshToken}____{httpToken}".LogWriteService(LogServiceCore.LogServiceCore_Refresh);

                context.Fail();
                return Task.CompletedTask;
            }

            //这里时数据库或者其他方式校验 
            var token = JwtUserFileService.GetRefreshToken(userid);
            if (token == refreshToken)
            {
                context.Succeed(requirement);
            }
            else
            {
                //$"403-3.refreshToken错误：{apiName}____{httpToken}____Token：{token}".LogWriteService(LogServiceCore.LogServiceCore_Refresh);

                context.Fail();
            }
            return Task.CompletedTask;
        }
    }
}
